/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package org.whuims.service.standard;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.whuims.entity.Term;
import org.whuims.repository.jpa.TermDao;

import java.util.List;
import java.util.Map;

// Spring Bean的标识.
@Component
// 类中所有public函数都纳入事务管理的标识.
@Transactional
public class TermService {

    private TermDao termDao;

    public Term getTerm(Long id) {
        return termDao.findOne(id);
    }

    public void save(Term entity) {
        termDao.save(entity);
    }

    public void delete(Long id) {
        termDao.delete(id);
    }

    public List<Term> getAllNews() {
        return (List<Term>) termDao.findAll();
    }

    public List<Term> findTopNews(int size) {
        Sort sort = new Sort(Direction.DESC, "id");
        PageRequest pr = new PageRequest(0, size, sort);
        return termDao.findAll(pr).getContent();
    }

    public Page<Term> getNewsList(Map<String, Object> searchParams, int pageNumber, int pageSize,
                                  String sortType) {
        PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
        return termDao.findAll(pageRequest);
    }

    /**
     * 创建分页请求.
     */
    private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
        Sort sort = null;
        if (sortType == null) sortType = "auto";
        if ("auto".equals(sortType)) {
            sort = new Sort(Direction.DESC, "id");
        } else if ("title".equals(sortType)) {
            sort = new Sort(Direction.ASC, "name");
        }

        return new PageRequest(pageNumber - 1, pagzSize, sort);
    }

    @Autowired
    public void setTermDao(TermDao termDao) {
        this.termDao = termDao;
    }
}
